package com.example.easytraffic.core;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

public class PeriodicTraffic implements Traffic{

	private long period;
	private TimeUnit periodTimeUnit;
	private Timer timer;
	private Traffic traffic;
	
	public PeriodicTraffic(Traffic traffic,
			long period, 
			TimeUnit periodTimeUnit) {
		super();
		this.timer = new Timer();
		this.period = period;
		this.periodTimeUnit = periodTimeUnit;
		this.traffic = traffic;
	}

	public void run() {
		long periodInMillis = periodTimeUnit.toMillis(period);
		timer.schedule(new TimerTask() {
			public void run() {
				try {
					traffic.run();
				} catch (TrafficEndedException e) {
					stop();
				}
			}
		}, 0, periodInMillis);
	}

	public void stop() {
		timer.cancel();
		traffic.stop();
	}
}
